package com.licheedev.serialtool222;

import android.widget.TextView;

import com.licheedev.serialtool222.assistant.SerialHelper;
import com.licheedev.serialtool222.assistant.bean.ComBean;
import com.licheedev.serialtool222.cmd4000.utils.Logs;

import java.io.IOException;
import java.security.InvalidParameterException;

import butterknife.BindView;

public class MainActivity extends BaseAppCompatActivity {

    @BindView(R.id.tv_test)
    TextView tv_test;

    private SerialControl ComA;


    @Override
    protected void initView() {
        ComA = new SerialControl();
        ComA.setPort("/dev/ttyACM0");
        ComA.setBaudRate("9600");

        OpenComPort(ComA);
        sendPortData(ComA,"CMDA");
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void onDestroy(){
        CloseComPort(ComA);
        super.onDestroy();
    }

    private void OpenComPort(SerialHelper ComPort) {
        try {
            ComPort.open();
        } catch (SecurityException e) {
            showToast("打开串口失败:没有串口读/写权限!");
        } catch (IOException e) {
            showToast("打开串口失败:未知错误!");
        } catch (InvalidParameterException e) {
            showToast("打开串口失败:参数错误!");
        }
    }

    //----------------------------------------------------关闭串口
    private void CloseComPort(SerialHelper ComPort){
        if (ComPort!=null){
            ComPort.stopSend();
            ComPort.close();
        }
    }

    //----------------------------------------------------串口发送
    private void sendPortData(SerialHelper ComPort, String sOut) {
        if (ComPort != null && ComPort.isOpen()) {
            //文本发数据
            ComPort.sendTxt(sOut);
            //16进制发数据
            //ComPort.sendHex(sOut);
        }
    }


    //----------------------------------------------------串口控制类
    private class SerialControl extends SerialHelper {

        public SerialControl() { }

        @Override
        protected void onDataReceived(final ComBean ComRecData) {
            final String address = new String(ComRecData.bRec);
            Logs.v("onDataReceived ===>"+address);

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_test.setText(address);
                }
            });
        }
    }
}
